package com.julian.delegatePattern.protectProxy;

import java.lang.reflect.Proxy;

public class MatchMakingTestDrive {

    public MatchMakingTestDrive() {
        initializeDatabase();
    }

    private void initializeDatabase() {
    }

    public static void main(String[] args) {
        MatchMakingTestDrive testDrive = new MatchMakingTestDrive();
        testDrive.drive();
    }

    private void drive() {
        PersonBean joe = getPersonFromDatabase("Joe JavaBean");
        PersonBean ownerProxy = getOwnerProxy(joe);
        System.out.println("Name is "+ ownerProxy.getName());
        ownerProxy.setInterests("bowling, Go");
        System.out.println("Interests set from owner proxy");
        try{
            ownerProxy.setHotOrNotRating(10);
        }catch (Exception e){
            System.out.println("can't set rating from owner proxy");
        }
        System.out.println("Rating is " + ownerProxy.getHotOrNotRating());
        PersonBean nonOwnerProxy = getNonOwnerProxy(joe);
        System.out.println("Name is "+ nonOwnerProxy.getName());
        try{
            nonOwnerProxy.setInterests("bowling, go");
        }catch (Exception e){
            System.out.println("Can't set interests from non owner proxy");
        }

        nonOwnerProxy.setHotOrNotRating(3);
        System.out.println("Rating set from non owner proxy");
        System.out.println("Rating is " + nonOwnerProxy.getHotOrNotRating());
    }

    private PersonBean getPersonFromDatabase(String joe_javaBean) {
        if (joe_javaBean.equals("Joe JavaBean")){
            PersonBean personBean = new PersonBeanImpl();
            personBean.setName("Joe JavaBean");
            personBean.setGender("woman");
            personBean.setInterests("cooking");
            personBean.setHotOrNotRating(10);
            return personBean;
        }
        return null;
    }

    private PersonBean getNonOwnerProxy(PersonBean personBean) {
        return (PersonBean) Proxy.newProxyInstance(personBean.getClass().getClassLoader(),
                personBean.getClass().getInterfaces(),
                new NonOwnerInvocationHandler(personBean)
                );
    }

    private PersonBean getOwnerProxy(PersonBean personBean) {
        return (PersonBean) Proxy.newProxyInstance(personBean.getClass().getClassLoader(),
                personBean.getClass().getInterfaces(),
                new OwnerInvocationHandler(personBean));
    }
}
